package com.study.common.util;

import lombok.extern.slf4j.Slf4j;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Map;

@Slf4j
public class PrintHelper {

  /**
   * jdbc数据源打印
   *
   * @param req
   * @param res
   * @param params
   * @param filePath
   * @param connection
   * @throws IOException
   * @throws Exception
   */
  public static void printPdf(HttpServletRequest req, HttpServletResponse res, Map<String, Object> params,
                              String filePath, Connection connection) throws Exception {
    log.info("开始打印");
    req.setCharacterEncoding("utf-8");
    res.setCharacterEncoding("utf-8");
    res.setContentType("text/html");
    res.setContentType("application/pdf");
    ClassPathResource resource = new ClassPathResource(filePath);
    if (!resource.exists()) {
      throw new Exception("模板-" + filePath + "不存在！");
    }
    InputStream is = resource.getInputStream();
    ServletOutputStream out = res.getOutputStream();
    JasperRunManager.runReportToPdfStream(is, out, params, connection);
    out.flush();
    out.close();
  }

  /**
   * javabean数据源打印
   *
   * @param req
   * @param res
   * @param params
   * @param filePath
   * @param jRBeanCollectionDataSource
   * @throws IOException
   * @throws JRException
   */
  public static void printPdfByJavaBean(HttpServletRequest req, HttpServletResponse res, Map<String, Object> params,
                                        String filePath, JRBeanCollectionDataSource jRBeanCollectionDataSource) throws Exception {
    log.info("开始打印");
    req.setCharacterEncoding("utf-8");
    res.setCharacterEncoding("utf-8");
    res.setContentType("text/html");
    res.setContentType("application/pdf");
    ClassPathResource resource = new ClassPathResource(filePath);
    if (!resource.exists()) {
      throw new Exception("模板-" + filePath + "不存在！");
    }
    InputStream is = resource.getInputStream();
    ServletOutputStream out = res.getOutputStream();
    JasperRunManager.runReportToPdfStream(is, out, params, jRBeanCollectionDataSource);
    out.flush();
    out.close();
    log.info("打印结束");
  }
}
